<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>权限管理</span>
        <div style="float: right">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleAdd"
          >
            添加权限
          </el-button>
        </div>
      </div>
      <el-form :inline="true" :model="queryParams" size="small">
        <el-form-item label="权限名称">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入权限名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="权限编码">
          <el-input
            v-model="queryParams.code"
            placeholder="请输入权限编码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="类型">
          <el-select
            v-model="queryParams.type"
            placeholder="请选择类型"
            clearable
          >
            <el-option
              v-for="dict in typeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleQuery"
          >
            搜索
          </el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 树表格区域 -->
    <el-card class="box-card" style="margin-top: 10px">
      <el-table
        v-loading="loading"
        :data="permissionList"
        style="width: 100%"
        row-key="id"
        border
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        class="adaptive-table"
        fit 
      >
        <el-table-column
          prop="name"
          label="权限名称"
          align="left"
          :min-width="120"  
        ></el-table-column>
        <el-table-column
          prop="code"
          label="权限编码"
          align="center"
          :min-width="120"
        ></el-table-column>
        <el-table-column
          prop="type"
          label="类型"
          align="center"
          :min-width="100"
        >
          <template #default="{ row }">
            {{mapTypeValue(getTypeLabel(row.type)) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="icon"
          label="图标"
          align="center"
          width="80"
        >
          <template #default="{ row }">
            <i v-if="row.icon" :class="row.icon"></i>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="path"
          label="路径"
          align="center"
          width="180"
        >
          <template #default="{ row }">
            <span v-if="row.path">{{ row.path }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="sort"
          label="排序"
          align="center"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          align="center"
          width="100"
        >
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          :min-width="130"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button
              size="small"
              type="text"
              icon="el-icon-plus"
              @click="handleAddChild(row)"
            >
              新增
            </el-button>
            <el-button
              size="small"
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改权限对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="600px"
      append-to-body
      @closed="handleDialogClosed"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="上级权限">
          <el-cascader
            v-model="form.parent_id"
            :options="permissionOptions"
            :props="{ checkStrictly: true, label: 'name', value: 'id', emitPath: false }"
            placeholder="请选择上级权限"
            clearable
            style="width: 100%"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input
            v-model="form.code"
            placeholder="请输入权限编码"
            :disabled="form.id !== undefined"
          />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type" @change="handleTypeChange">
            <el-radio
              v-for="dict in typeOptions"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.type === 'menu'" label="路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入菜单路径" />
        </el-form-item>
        <el-form-item v-if="form.type !== 'button'" label="图标" prop="icon">
          <el-input v-model="form.icon" placeholder="请输入图标类名">
            <template slot="append">
              <i v-if="form.icon" :class="form.icon"></i>
              <span v-else>无图标</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="9999"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPermissionList,
  getPermissionTree,
  getPermissionDetail,
  addPermission,
  editPermission,
  deletePermission
} from '@/api/permission'

export default {
  name: 'Permission',
  data() {
    return {
      // 遮罩层
      loading: false,
      // 权限表格数据
      permissionList: [],
      // 弹出层标题
      title: '添加权限',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        name: undefined,
        code: undefined,
        type: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 状态数据字典
      statusOptions: [
        {
          value: 1,
          label: '正常'
        },
        {
          value: 0,
          label: '停用'
        }
      ],
      // 类型数据字典
      typeOptions: [
        {
          value: 'module',
          label: '模块'
        },
        {
          value: 'menu',
          label: '菜单'
        },
        {
          value: 'button',
          label: '按钮'
        }
      ],
      // 权限树选项
      permissionOptions: [],
      // 表单校验
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限编码不能为空', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9_:.]+$/, message: '权限编码只能包含字母、数字、下划线、冒号和点', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '权限类型不能为空', trigger: 'change' }
        ],
        sort: [
          { required: true, message: '排序不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询权限列表 */
    getList() {
      this.loading = true
      getPermissionTree(this.queryParams).then(response => {
        this.permissionList = response.data
        this.loading = false
        // 获取完整权限树用于级联选择器
        this.getPermissionTreeOptions()
      })
    },
    /** 获取权限树选项 */
    getPermissionTreeOptions() {
      getPermissionTree().then(response => {
        // 构建顶级节点
        this.permissionOptions = [{
          id: 0,
          name: '顶级权限',
          children: response.data
        }]
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        name: undefined,
        code: undefined,
        type: undefined,
        status: undefined
      }
      this.handleQuery()
    },
    /** 状态修改 */
    handleStatusChange(row) {
      const text = row.status === 1 ? '启用' : '停用'
      this.$confirm(`确认要${text}权限"${row.name}"吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return editPermission({ id: row.id, status: row.status })
      }).then(() => {
        this.$message.success(`${text}成功`)
      }).catch(() => {
        row.status = row.status === 1 ? 0 : 1
      })
    },
    /** 添加按钮操作 */
    handleAdd() {
      this.reset()
      this.getPermissionTreeOptions()
      this.form.parent_id = 0
      this.open = true
      this.title = '添加权限'
    },
    /** 添加子权限按钮操作 */
    handleAddChild(row) {
      this.reset()
      this.getPermissionTreeOptions()
      this.form.parent_id = row.id
      this.open = true
      this.title = '添加子权限'
    },
    /** 编辑按钮操作 */
    handleEdit(row) {
      this.reset()
      this.getPermissionTreeOptions()
      getPermissionDetail(row.id).then(response => {
        const originData = response.data
        console.log('接口返回数据:', originData) // 添加调试日志
        this.form = {
          ...originData,
          name: originData.name || '', // 确保name字段存在
          type: this.mapTypeValue(originData.type)
        }
        
        this.open = true
        this.title = '编辑权限'
      })
    },
    // 新增类型转换方法
    mapTypeValue(type) {
      const typeMap = {
        1: '菜单',
        2: '按钮',
        3: '模块'
      }
      return typeMap[type] || type
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(`确认删除权限"${row.name}"吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return deletePermission(row.id)
      }).then(() => {
        this.getList()
        this.$message.success('删除成功')
      })
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        code: undefined,
        parent_id: 0,
        type: 'menu',
        path: undefined,
        icon: undefined,
        sort: 0,
        status: 1,
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 重置表单 */
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
    },
    /** 对话框关闭时的回调 */
    handleDialogClosed() {
      this.reset()
    },
    /** 类型变更处理 */
    handleTypeChange(value) {
      if (value === 'button') {
        this.form.icon = undefined
        this.form.path = undefined
      }
    },
    /** 获取类型标签 */
    getTypeLabel(type) {
      const found = this.typeOptions.find(item => item.value === type)
      return found ? found.label : type
    },
    /** 提交按钮 */
    submitForm() {
      console.log('提交前表单数据:', JSON.parse(JSON.stringify(this.form))) // 添加请求日志
      this.$refs.form.validate(valid => {
       
        if (valid) {
          if (this.form.id !== undefined) {
            editPermission(this.form).then(response => {
              this.$message.success('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addPermission(this.form).then(response => {
              this.$message.success('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.box-card {
  margin-bottom: 10px;
}

.adaptive-table {
  width: 100%;
  position: relative;

  ::v-deep .el-table__header-wrapper,
  ::v-deep .el-table__body-wrapper {
    min-width: fit-content;  
  }

  ::v-deep .el-table__cell {
    white-space: nowrap;
    padding: 8px 12px;
  }

  @media (max-width: 1200px) {
    ::v-deep .el-table__cell {
      min-width: 100px;
    }
  }

  @media (max-width: 768px) {
    ::v-deep [aria-hidden="true"] {
      display: none;  
    }
    ::v-deep .el-table__cell {
      min-width: 80px;
      padding: 6px 8px;
    }
    ::v-deep .el-button--small {
      padding: 5px;
    }
  }
}
</style> 